//
//  NetworkTools.swift
//  Super_WeiBo
//
//  Created by SuperMac on 16/3/21.
//  Copyright © 2016年 lc. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {

    static let tools : NetworkTools = {
        let url = NSURL(string: "https://api.weibo.com/")
        let t = NetworkTools(baseURL: url)
        t.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript" , "text/plain") as? Set<String>
        return t
    }()
    
    class func shareNetworkTools() -> NetworkTools {
        return tools
    }
    
    /**
     发送微博
     
     - parameter text:            微博文本
     - parameter image:           微博图片
     - parameter successCallback: 成功回调
     - parameter failCallback:    失败回调
     */
    func sendStatus(text: String, image: UIImage?, successCallback: (status: Status) -> (), errorCallback: (error: NSError) -> ())
    {
        // 接口基地址
        var path = "2/statuses/"
        // 请求参数
        let params = ["access_token": (UserAccount.loadAccount()?.access_token!)!, "status": text]
        if image != nil
        {// 发送图片微博
            // 拼接接口
            path += "upload.json"
            POST(path, parameters: params, constructingBodyWithBlock: { (formData) in
                // 讲数据转换为二进制
                let data = UIImagePNGRepresentation(image!)
                // 上传数据
                formData.appendPartWithFileData(data!, name: "pic", fileName: "LCWeiBo.png", mimeType: "application/octet-stream")
                }, success: { (_, JSON) in
                    successCallback(status: Status(dict: JSON as! [String: AnyObject]))
                }, failure: { (_, error) in
                    errorCallback(error: error)
            })
        }
        else
        {// 发送文本微博
            // 拼接接口
            path = "update.json"
            POST(path, parameters: params, success: { (_, JSON) in
                
                successCallback(status: Status(dict: JSON as! [String: AnyObject]))
                
            }) { (_, error) in
                errorCallback(error: error)
            }
        }
    }
    
}
 